import axios from 'axios';
import logger from '../../common/logger';
import { SimJobStatus } from '../model/simulation/type';
import { SimulationJobDto } from '../model/simulation/dtos';
import { postRetry } from '../../common/retry';
import moment from 'moment';

export class SimulationResultProcessor {
  constructor() {}
  async handle(job: SimulationJobDto) {
    const resultCallbackEndpoint = job.notificationCallback;
    const request = {
      businessId: job.businessId,
      jobId: job.id,
      success: job.status === SimJobStatus.Succeed ? true : false,
      message: job.message,
      parameters: job.spec?.parameters,
      result: job.result,
      info: {
        startTime: moment(job.startedAt).format('yyyy-MM-DD HH:mm:ss'),
        runTime: moment(job.finishedAt).diff(moment(job.startedAt), 'seconds'),
        endTime: moment(job.finishedAt).format('yyyy-MM-DD HH:mm:ss')
      }
    };
    const response = await postRetry(resultCallbackEndpoint, request);
    const { success } = response.data;
    if (success) {
      logger.info(`simulation job(id=${job.id}) succeed result sync to stream node(${job.userId}/${job.appId}/${job.nodeId}) succeed`);
      // await jobRepo.delete(job.id);
    } else {
      logger.error(`simulation job(id=${job.id}) succeed result sync to stream node(${job.userId}/${job.appId}/${job.nodeId}) failed`);
    }
  }
}